//------------------------------------------------------------------------------
#include <QtDebug>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QUrl>
#include <QEventLoop>
#include <libqt4json.h>
#include "CTomcatClient.h"
#include "CResponse.h"
#include "CProfils.h"
#include "CProfil.h"
#include "CAuthentificationRequestData.h"
#include "CGetSchemaRequestData.h"
//------------------------------------------------------------------------------
CTomcatClient::CTomcatClient(void) {
	CProfils *profils=CProfils::getInstance();
	CProfil *profil=profils->getCurrentProfil();
	
	if(profil == 0) {
		return;
	}
	
	baseUrl=profil->getJasper()+"/EntryPoint";
	dossier=profil->getBase();
}
//------------------------------------------------------------------------------
bool CTomcatClient::authenticate(QString userName, QString passWord) {
	CRequest request;
	CAuthentificationRequestData authRequest;
	QVariant result;
	
	authRequest.setUserName(userName);
	authRequest.setPassWord(passWord);
	
	request.setData(&authRequest);
	
	if(call(&request, "Authentification", result)) {
		QVariantList l=qvariant_cast<QVariantList>(result);
		
		if(l.size() == 1 && l.at(0).type() == QVariant::Map) {
			QVariantMap m=qvariant_cast<QVariantMap>(l.at(0));
			
			if(m.value("result").toString() == "OK") {
				CGlobal::setToken(m.value("token").toString());
				return true;
			}else {
				lastError=tr("Connexion impossible, vérifiez vos nom d'utilisateur et mot de passe");
			}
		}else {
			lastError=tr("Message serveur incorrect");
		}
	}
	
	return false;
}
//------------------------------------------------------------------------------
bool CTomcatClient::report(CRequest *request, QByteArray &datas, QString &contentType) {
	QVariant result;

	if(call(request, "Report", result)) {
		QVariantList l=qvariant_cast<QVariantList>(result);
	
		if(l.size() == 1 && l.at(0).type() == QVariant::Map) {
			QVariantMap m=qvariant_cast<QVariantMap>(l.at(0));
			
			datas=QByteArray::fromBase64(m.value("content").toString().toUtf8());
			contentType=m.value("contentType").toString();
			
			return true;
		}else {
			lastError=tr("Message serveur incorrect");
		}
	}
	
	return false;
}
//------------------------------------------------------------------------------
bool CTomcatClient::servletVersion(QString &version) {
	CRequest request;
	CVoidRequestData vrd;
	QVariant result;
	
	request.setToken(CGlobal::getToken());
	request.setData(&vrd);
	
	if(call(&request, "ServletVersion", result)) {
		QVariantList l=qvariant_cast<QVariantList>(result);
	
		if(l.size() == 1 && l.at(0).type() == QVariant::Map) {
			QVariantMap m=qvariant_cast<QVariantMap>(l.at(0));
			
			version=m.value("version").toString();
			return true;
		}else {
			lastError=tr("Message serveur incorrect");
		}
	}
	return false;
}
//------------------------------------------------------------------------------
bool CTomcatClient::databaseVersion(QString &version) {
	CRequest request;
	CVoidRequestData vrd;
	QVariant result;
	
	request.setToken(CGlobal::getToken());
	request.setData(&vrd);
	
	if(call(&request, "DatabaseVersion", result)) {
		QVariantList l=qvariant_cast<QVariantList>(result);
	
		if(l.size() == 1 && l.at(0).type() == QVariant::Map) {
			QVariantMap m=qvariant_cast<QVariantMap>(l.at(0));
			
			version=m.value("version").toString();
			return true;
		}else {
			lastError=tr("Message serveur incorrect");
		}
	}
	return false;
}
//------------------------------------------------------------------------------
bool CTomcatClient::getConfig(QVariantMap &config) {
	CRequest request;
	CVoidRequestData vrd;
	QVariant result;
	
	request.setToken(CGlobal::getToken());
	request.setData(&vrd);
	
	if(call(&request, "GetConfig", result)) {
		QVariantList l=qvariant_cast<QVariantList>(result);
	
		if(l.size() == 1 && l.at(0).type() == QVariant::Map) {
			config=qvariant_cast<QVariantMap>(l.at(0));
	
			return true;
		}else {
			lastError=tr("Message serveur incorrect");
		}
	}
	return false;
}
//------------------------------------------------------------------------------
bool CTomcatClient::getSchema(QString tableName, QVariantMap &schema) {
	CRequest request;
	CGetSchemaRequestData gsrd;
	QVariant result;
	
	gsrd.setTableName(tableName);
	
	request.setToken(CGlobal::getToken());
	request.setData(&gsrd);
	
	if(call(&request, "GetSchema", result)) {
		QVariantList l=qvariant_cast<QVariantList>(result);
	
		if(l.size() == 1 && l.at(0).type() == QVariant::Map) {
			schema=qvariant_cast<QVariantMap>(l.at(0));
	
			return true;
		}else {
			lastError=tr("Message serveur incorrect");
		}
	}
	return false;
}
//------------------------------------------------------------------------------
bool CTomcatClient::call(CRequest* request, QString action, QVariant &result) {
	QNetworkAccessManager networkAccessManager;
	libqt4json::CJson json;
	QString url=baseUrl;
	bool ok=false;
	QString sJson;
	
	url+="?action="+action+"&dossier="+dossier;
	
	QNetworkRequest networkRequest;
	networkRequest.setUrl(QUrl(url));
		
	connect(&networkAccessManager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError> & )), this, 
		SLOT(onSslErrorHandler(QNetworkReply*, const QList<QSslError> & )));
		
	sJson=json.toString(QVariant::fromValue((QObject *)request));
	
	qDebug() << sJson;
	
	QByteArray postData=sJson.toUtf8();
	
	QNetworkReply *reply=networkAccessManager.post(networkRequest, postData);
	QNetworkReply::NetworkError error;
	QEventLoop loop;
	connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
	loop.exec();
	
	error=reply->error();
	if(error == QNetworkReply::NoError) {
		QByteArray receiveData=reply->readAll();
		sJson=QString(receiveData);
	
		qDebug() << sJson;
		
		result=json.fromString(sJson, ok);
		lastError="";
		if(!ok) {
			lastError=tr("Unable to parse JSon response");
		}else {
			CResponse *r=CResponse::fromVariant(result);
			result=r->getData();
			
			if(r->getErrorCode() != 0) {
				ok=false;
				lastError=r->getErrorMessage();
			}
			
			delete r;
		}
	}else {
		lastError=reply->errorString();
	}
	
	return ok;
}
//------------------------------------------------------------------------------
void CTomcatClient::onSslErrorHandler(QNetworkReply* qnr, const QList<QSslError> & ) {
	qnr->ignoreSslErrors();
}
//------------------------------------------------------------------------------